package com.kingyea.app.market.userappmenu.controller;

import com.alibaba.fastjson.JSON;
import com.kingyea.app.market.appBaseInfo.bean.AppBaseInfo;
import com.kingyea.app.market.appBaseInfo.service.AppBaseInfoService;
import com.kingyea.app.market.appExtendInfo.service.AppExtendInfoService;
import com.kingyea.app.market.appauthorization.bean.AppAuthorization;
import com.kingyea.app.market.appauthorization.bean.AppAuthorizationPo;
import com.kingyea.app.market.authorize.service.AuthorizeService;
import com.kingyea.app.market.client.*;
import com.kingyea.app.market.role.Role;
import com.kingyea.app.market.userappmenu.bean.DesktopMenuVo;
import com.kingyea.app.market.userappmenu.bean.UserAppMenu;
import com.kingyea.app.market.userappmenu.service.UserAppMenuService;
import com.kingyea.app.market.utils.ExceptionConditions;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.app.market.utils.page.PageInfo;
import com.kingyea.app.market.versionInfo.bean.VersionInfo;
import com.kingyea.app.market.versionInfo.service.VersionInfoService;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.aspect.NotResult;
import com.kingyea.mobilepolice.user.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hx
 * @version v1.0.0
 * @description UserAppMenu 控制层
 * @date Created in 2018-04-24 11:42:24
 */
@RequestMapping(value = "/userAppMenu")
@RestController
public class UserAppMenuController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAppMenuController.class);

    @Autowired
    private UserAppMenuService userAppMenuService;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private AppBaseInfoService appBaseInfoService;
    @Autowired
    private AppExtendInfoService appExtendInfoService;
    @Autowired
    private VersionInfoService versionInfoService;
    @Autowired
    private MarketServiceClient marketServiceClient;
    @Autowired
    private OrganizationServiceClient organizationServiceClient;
    @Autowired
    private DictionaryServiceServiceClient dictionaryServiceServiceClient;
    @Autowired
    private RoleServiceClient roleServiceClient;

    /**
     * 查询全部
     *
     * @param
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public List<UserAppMenu> list() throws Exception {
        return userAppMenuService.list(null);
    }

    /**
     * 通过ID查找对象
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public UserAppMenu detail(@PathVariable Integer id) throws Exception {
        return userAppMenuService.getById(id);
    }

    /**
     * 获取当前用户可安装的app
     */
    @NotResult
    @PostMapping(value = "/getAppByUser")
    public Object getAppByUser(@RequestBody Map<String, Object> obj) throws Exception {
        Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
        // 获取用户失败，返回空数组
        Map<String, Object> reobj = new HashMap<>();
        if (currentUserInfo.getData() == null) {
            reobj.put("data", new ArrayList<>());
            return reobj;
        }
        User currUser = currentUserInfo.getData();
        obj.put("user", currUser.getUserId());
        // 当前用户已有权限的appCode
        // 根据userId查部门

        // 根据userId查角色
        Object roleObj = roleServiceClient.detail(currUser.getUserId());
        Result roleResult = JSON.parseObject(JSON.toJSONString(roleObj), Result.class);
        List<Role> role = new ArrayList<>();
        if (roleResult.getData() != null) {
            role = JSON.parseArray(JSON.toJSONString(roleResult.getData()), Role.class);
        }
        List<Integer> roleList = new ArrayList<>();
        role.forEach(vo -> roleList.add(vo.getId()));
        // 根据userId查警种
        // 查权限
        AppAuthorizationPo appAuthorization = new AppAuthorizationPo();
        appAuthorization.setOrgSerialNo(currUser.getOrgSerialNo());
        if (roleList.size() > 0) {
            appAuthorization.setRoleIds(roleList);
        }
        appAuthorization.setPolice(Integer.valueOf(currUser.getJobCategory()));
        appAuthorization.setUserId(currUser.getUserId());
        Object appAuthorizationObj = marketServiceClient.getbyUser(appAuthorization);
        Result re = JSON.parseObject(JSON.toJSONString(appAuthorizationObj), Result.class);
        List<AppAuthorization> authorizeList = new ArrayList<>();
        if (re.getData() != null) {
            authorizeList = JSON.parseArray(JSON.toJSONString(re.getData()), AppAuthorization.class);
        }
        // 授权数据为空 返回空数组
        if (authorizeList.size() <= 0) {
            reobj.put("data", new ArrayList<>());
            return reobj;
        }
        List<String> appCodes = new ArrayList<>();
        for (AppAuthorization authorize : authorizeList) {
            appCodes.add(authorize.getAppCode());
        }
        //已有权限的appCode+已发布的 appCode
        obj.put("publishFlag", 1);
        obj.put("appCodes", appCodes);
        obj.put("pageNum", 1);
        obj.put("pageSize", 10000);
        PageInfo pageInfo = (PageInfo) appBaseInfoService.list(obj);
        // 已有权限的appCode+已发布的 appCode为空 返回空数组
        if (pageInfo.getList().size() <= 0) {
            reobj.put("data", new ArrayList<>());
            return reobj;
        }
        List<AppBaseInfo> appBaseInfoList = pageInfo.getList();
        appCodes = new ArrayList<>();
        for (AppBaseInfo appBaseInfo : appBaseInfoList) {
            appCodes.add(appBaseInfo.getAppCode());
        }
        obj = new HashMap<>();
        obj.put("appCodes", appCodes);
        obj.put("versionType", 1);
        obj.put("currentVersion", 1);
        obj.put("pageNum", 1);
        obj.put("pageSize", 10000);
        PageInfo<VersionInfo> list = versionInfoService.list(obj);
        // 查询对应的版本信息为空 返回空数组
        if (list.getList().size() <= 0) {
            reobj.put("data", new ArrayList<>());
            return reobj;
        }
        List<VersionInfo> versionInfoList = list.getList();
        //最终返回的集合
        List<DesktopMenuVo> desktopMenuVoList = new ArrayList<>();
        for (AppBaseInfo appBaseInfo : appBaseInfoList) {
            for (VersionInfo versionInfo : versionInfoList) {
                if (appBaseInfo.getAppCode().equals(versionInfo.getAppCode())) {
                    DesktopMenuVo vo = new DesktopMenuVo();
                    vo.setAppCode(appBaseInfo.getAppCode());
                    vo.setLogo(appBaseInfo.getLogoImage());
                    vo.setName(appBaseInfo.getAppName());
                    vo.setUrl(versionInfo.getAccessUrl());
                    vo.setRemark(appBaseInfo.getRemark());
                    desktopMenuVoList.add(vo);
                }
            }
        }
        UserAppMenu userAppMenu = new UserAppMenu();
        userAppMenu.setUserId(currUser.getUserId());
        List<UserAppMenu> userAppMenuList = userAppMenuService.list(userAppMenu);
        // 添加返回字段 用来判断是否已经下载
        for (DesktopMenuVo vo : desktopMenuVoList) {
            vo.setIsInstall(0);
            for (UserAppMenu app : userAppMenuList) {
                if (vo.getAppCode().equals(app.getAppCode())) {
                    vo.setIsInstall(1);
                }
            }
        }
        obj = new HashMap<>();
        obj.put("data", desktopMenuVoList);
        return obj;
    }

    /**
     * 已安装的app？
     */
    @NotResult
    @GetMapping(value = "/myApp")
    public Object myApp() throws Exception {
        Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
        Map<String, Object> reobj = new HashMap<>();
        if (currentUserInfo.getData() == null) {
            reobj.put("data", new ArrayList<>());
            return reobj;
        }
        User data = currentUserInfo.getData();
        return userAppMenuService.myApp(data.getUserId());
    }

    /**
     * 创建
     *
     * @param userAppMenu
     * @return
     */
    @NotResult
    @PostMapping(value = "/create")
    public UserAppMenu create(@RequestBody UserAppMenu userAppMenu) throws Exception {
        ExceptionConditions.checkStringNotEmpty(userAppMenu.getAppCode(), StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkStringNotEmpty(userAppMenu.getRegion(), StateCode.NO_ARGUMENT_ERROR);
        ExceptionConditions.checkNotNull(userAppMenu.getDesktop(), StateCode.NO_ARGUMENT_ERROR);
        Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
        User data = currentUserInfo.getData();
        userAppMenu.setUserId(data.getUserId());
        return userAppMenuService.save(userAppMenu);
    }

    /**
     * 更新
     *
     * @param userAppMenu
     * @return
     */
    @NotResult
    @PostMapping(value = "/update")
    public UserAppMenu update(@RequestBody UserAppMenu userAppMenu) throws Exception {
        return userAppMenuService.update(userAppMenu);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @NotResult
    @PostMapping(value = "/delete/{id}")
    public int delete(@PathVariable Integer id) throws Exception {
        return userAppMenuService.deleteById(id);
    }

    @NotResult
    @GetMapping(value = "/test")
    public Object test() {
        System.out.println("sysoooooooooooo222222222222222222oooooooooo");
        List list = new ArrayList();
        List appList = new ArrayList();
        Map<String, String> app = new HashMap<>();
        app.put("title1", "应用市场管理");
        app.put("title2", "应用汇总d");
        appList.add(app);
        Map<String, String> app2 = new HashMap<>();
        app2.put("title1", "应用市场管理");
        app2.put("title2", "应用汇总");
        appList.add(app2);
        Map<String, Object> region = new HashMap<>();
        region.put("region", appList);
        Map<String, Object> desktop = new HashMap<>();
        desktop.put("desktop", region);
        Map<String, Object> desktop1 = new HashMap<>();
        desktop1.put("desktop1", region);
        list.add(desktop);
        list.add(desktop1);
        return PageInfo.getPageInfo(list);
        /*Result<User> currentUserInfo = userServiceClient.getCurrentUserInfo();
//		User data = currentUserInfo.getData();
        obj.put("user", "9efa2aa6-ccf5-428a-8376-7a7b6aa66dd4");
        // 当前用户已有权限的appCode
        List<Authorize> authorizeList = authorizeService.list(obj);
        List<String> appCodes = new ArrayList<>();
        for (Authorize authorize : authorizeList) {
            appCodes.add(authorize.getAppCode());
        }
        //已有权限的appCode+已发布的 appCode
        obj.put("publishFlag", 1);
        obj.put("appCodes", appCodes);
        obj.put("pageNum", 1);
        obj.put("pageSize", 10000);
        PageInfo pageInfo = (PageInfo) appBaseInfoService.list(obj);
        List<AppBaseInfo> appBaseInfoList = pageInfo.getList();
        appCodes = new ArrayList<>();
        for (AppBaseInfo appBaseInfo : appBaseInfoList) {
            appCodes.add(appBaseInfo.getAppCode());
        }
        obj = new HashMap<>();
        // 查询web的appCode根据已发布的appCode
        obj.put("appTerminal", 1);
        obj.put("appCodes", appCodes);
        List<AppExtendInfo> appExtendInfoList = appExtendInfoService.getList(obj);
        appCodes = new ArrayList<>();
        for (AppExtendInfo appExtendInfo : appExtendInfoList) {
            appCodes.add(appExtendInfo.getAppCode());
        }
        obj = new HashMap<>();
        obj.put("appCodes", appCodes);
        obj.put("versionType", 1);
        obj.put("currentVersion", 1);
        PageInfo<VersionInfo> list = versionInfoService.list(obj);
        List<VersionInfo> versionInfoList = list.getList();
        //最终返回的集合
        List<DesktopMenuVo> desktopMenuVoList = new ArrayList<>();
        for (AppBaseInfo appBaseInfo : appBaseInfoList) {
            for (VersionInfo versionInfo : versionInfoList) {
                if(appBaseInfo.getAppCode().equals(versionInfo.getAppCode())){
                    DesktopMenuVo vo = new DesktopMenuVo();
                    vo.setAppCode(appBaseInfo.getAppCode());
                    vo.setLogo(appBaseInfo.getLogoImage());
                    vo.setName(appBaseInfo.getAppName());
                    vo.setUrl(versionInfo.getAccessUrl());
                    desktopMenuVoList.add(vo);
                }
            }
        }
        UserAppMenu userAppMenu = new UserAppMenu();
        userAppMenu.setUserId("9efa2aa6-ccf5-428a-8376-7a7b6aa66dd4");
        List<UserAppMenu> userAppMenuList = userAppMenuService.list(userAppMenu);
        for (DesktopMenuVo vo:desktopMenuVoList) {
            vo.setIsInstall(0);
            for (UserAppMenu app:userAppMenuList) {
                if(vo.getAppCode().equals(app.getAppCode())){
                    vo.setIsInstall(1);
                }else{
                    vo.setIsInstall(0);
                }
            }
        }
        obj = new HashMap<>();
        obj.put("data", desktopMenuVoList);
//		List<AppExtendInfo> listss = JSON.parseArray(JSON.toJSONString(list), AppExtendInfo.class);
        return obj;*/
    }

}
